#coding=utf-8
from uliweb import expose, functions
from uliweb.mail import Mail
import socket
#import sys  
#reload(sys)  
#sys.setdefaultencoding('utf8')  
from uliweb.orm import get_model,Begin,Commit,Rollback

from subprocess import Popen, PIPE
import re
import simplejson
import platform

def cmdpopen(cmd):
    '''
    shell命令调用块
    '''
    return Popen(cmd, shell=True, close_fds=True, stdout=PIPE, stderr=PIPE)

def __begin__():
    """
    用户验证
    """
    from uliweb import functions
    return functions.require_login()

########################################################################
@expose('/webproject')
class WebProject(object):
    """
    仓库管理操作
    """
    
    #----------------------------------------------------------------------
    def __init__(self):
        """Constructor"""
        from uliweb.orm import get_model
        self.subversionmodel = get_model('subversion')
        self.usermodel = get_model('user')    
    
    def subversionlist(self):
        """
        仓库列表操作
        """
        return {}

    def subversionlistadd(self):
        """
        仓库列表操作
        """
        data = []
    
        #列出非管理员用户的非锁定账户
        ormdata = self.usermodel.filter(self.usermodel.c.is_superuser == 0).filter(self.usermodel.c.locked == 0).filter().fields('id','nickname')
    
        for i in ormdata:
            select_data =  '<option value="' + str(i.id) + '">' + i.nickname + '</option>'
            data.append(select_data)
    
        return {"html_user":"".join(data)}
    
    def subversionlistedit(self):
        """
        仓库列表操作
        """
        _id = request.GET.get("id")
        #如果_id不存在，就是url非法输入，就提示错误
        if _id == None or _id == "":
            return json({"status":500,"msg":"URL错误"})
        
        #从redis获取数据
        ormdata = functions.get_object(self.subversionmodel, _id, cache=True, use_local=True)
        
        data = []
        #查找出非管理员的用户
        ormdata_user = self.usermodel.filter(self.usermodel.c.is_superuser == 0).filter(self.usermodel.c.locked == 0).filter().fields('id','nickname')
        
        for i in ormdata_user:
            if i.id in ormdata.users.ids():
                select_data =  '<option value="' + str(i.id) + '" selected>' + i.nickname + '</option>'
            else:
                select_data =  '<option value="' + str(i.id) + '">' + i.nickname + '</option>'
            data.append(select_data)


        #将对象传给模版
        return {"ormdata":ormdata,"html_user":"".join(data)} 
    
    def subversionlistsave(self):
        """
        保存添加,修改仓库信息
        """
        
        _id = request.POST.get('id')
        
        svn_name = request.POST.get('svn_name')
        svn_username = request.POST.get('svn_username')
        svn_passwd = request.POST.get('svn_passwd')
        svn_url = request.POST.get('svn_url')
        svn_webdir_server = request.POST.get('svn_webdir_server')
        rsync_ignore_dir = request.POST.get('rsync_ignore_dir')
        svn_webip_client = request.POST.get('svn_webip_client')
        rsync_module = request.POST.get('rsync_module')
        users = request.POST.getlist('users')
        
        #用于标识是新增还是修改.默认新增True
        flag=True
        
        if _id == None:
            ormdata = self.subversionmodel(svn_name=svn_name,
                                           svn_username=svn_username,
                                           svn_passwd=svn_passwd,
                                           svn_url=svn_url,
                                           svn_webdir_server=svn_webdir_server,
                                           rsync_ignore_dir=rsync_ignore_dir,
                                           rsync_module=rsync_module,
                                           svn_webip_client = svn_webip_client
                                           )
        else:
            ormdata = functions.get_object(self.subversionmodel, _id, cache=True, use_local=True)
            ormdata.svn_name = svn_name
            ormdata.svn_username=svn_username
            ormdata.svn_passwd=svn_passwd
            ormdata.svn_url=svn_url
            ormdata.svn_webdir_server=svn_webdir_server
            ormdata.rsync_ignore_dir=rsync_ignore_dir
            ormdata.rsync_module=rsync_module
            ormdata.svn_webip_client=svn_webip_client
        
        Begin()
    
        try:
            ormdata.save()
    
            #多对多操作
            ormdata_user = list(self.usermodel.filter(self.usermodel.c.id.in_(users)).filter().fields('id'))
    
            if flag:
                ormdata.users.add(ormdata_user)
            else:
                ormdata.users.update(ormdata_user)
    
            Commit()
            return json({"status":200,"msg":"添加成功"}) 
    
        except:
            Rollback()
            return json({"status":500,"msg":"保存失败"})
    
    def subversionlistupdate(self):
        """
        更新服务器源
        """

        if request.method == 'GET':
            _id = request.GET.get('id')
            return {"id":_id}
        else:
            _id = request.POST.get('id')
            svn_ver = request.POST.get('svn_ver')
    
            if platform.system() == "Windows":
                return json({"status":500,"msg":"不支持win平台，请使用Linux"})  
            
            ormdata = functions.get_object(self.subversionmodel, _id, cache=True, use_local=True)
            
            svn_url = ormdata.svn_url
            svn_username = ormdata.svn_username
            svn_passwd = ormdata.svn_passwd
            svn_webdir_server = ormdata.svn_webdir_server
            
            if svn_ver == "" or svn_ver == None:
                cmd = 'svn co --non-interactive ' + svn_url + ' --username ' + svn_username +  \
                    ' --password ' + svn_passwd + ' ' + svn_webdir_server
            else:
                cmd = 'svn co --non-interactive -r ' + svn_ver + ' ' + svn_url + ' --username ' + svn_username +  \
                            ' --password ' + svn_passwd + ' ' + svn_webdir_server
    
  
            stdoutdata, stderrdata = cmdpopen(cmd).communicate()
            
            if len(stderrdata) == 0:   
                
                ormdata.svn_comment = stdoutdata.split('\n')[-2]
                           
            else:
                #print "stderrdata======>" + stderrdata
                
                ormdata.svn_comment = stderrdata
            
            try:
                ormdata.save()
                
                return json({"status":200,"msg":"更新成功"})
            except:
                return json({"status":500,"msg":"更新失败"})    
    
    def subversionlistdel(self):
        """
        删除仓库
        """
        _id = request.POST.get('id')
    
        for i in _id.split(','):
    
            #通过id，获取权限信息
            ormdata = functions.get_object(self.subversionmodel, _id, cache=True, use_local=True)

            #获取所有用户id
            usersid = ormdata.users.ids()
    
            ormdata.users.remove(usersid)
    
            ormdata.delete()
    
        return json({"status":200,"msg":"删除成功"})
     
    
    def codepublish(self):
        """
        代码发布
        """

        if platform.system() == "Windows":
            return json({"status":500,"msg":"不支持win平台，请使用Linux"}) 

        _id = request.POST.get('id[]')

        #得到1条符合的数据
        ormdata = functions.get_object(self.subversionmodel, _id, cache=True, use_local=True)
        
        #本地源目录
        svn_webdir_server = ormdata.svn_webdir_server
        #远程web的ip
        svn_webip_client = ormdata.svn_webip_client
        #rsync模块
        rsync_module = ormdata.rsync_module
        
        #忽略的目录
        ignore_dir = ormdata.rsync_ignore_dir
                
        ignore_dir_all = []
        if ignore_dir != "":
            for i in ignore_dir.split(','):
                ignore_dir_all.append("--exclude=" + i)
                
        info = []
        for ip in svn_webip_client.split(','):

            if ip == "" or ip == "\n":
                continue
            
            #/usr/bin/rsync -vzrtopg --exclude=.svn/* --exclude=Runtime/* --exclude="Conf/*" --exclude=error/* --exclude=css/* --exclude=Html/* --exclude=log/* --exclude=svn/* $1 1.1.1.1.::xkqquse/
            #svn update http://192.168.1.246:81/svn/ahhouseconvert --username xxx  --xxxx share /htdoc/web/ah.com/server/

            cmd = '/usr/bin/rsync -vzrtopg --exclude=.svn ' + " ".join(ignore_dir_all) + ' ' + svn_webdir_server + ' ' + ip + "::" + rsync_module

            stdoutdata, stderrdata = cmdpopen(cmd).communicate()
            
            if len(stderrdata) == 0:
                info.append(ip + "====>ok")
                           
            else:
                info.append(ip + "====>" + stderrdata)
                
        return json({"msg":"<br>".join(info),"status":200})
        
                    
    def execcmd(self):
        """
        """
        if request.method == 'GET':
            return {}
        else:
            cmd = request.POST.get('execcmd')
            
            stdoutdata, stderrdata = cmdpopen(cmd).communicate()
            
            if len(stderrdata) == 0:
                
                return json({"msg":stdoutdata,"success":200})
            else:
                return json({"msg":stderrdata,"error":500})
                
        